package com.zz.kt.utils;

import com.zz.kt.exception.GlobalExceptionHandler;
import com.zz.kt.utils.JwtHelper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ClaimsMutator;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserLoginInterceptor implements HandlerInterceptor {

    private RedisTemplate redisTemplate;

    public UserLoginInterceptor(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        this.initUserLoginVo(request);
        return true;
    }

    private void initUserLoginVo(HttpServletRequest request){
        String token = request.getHeader("token");

        System.out.println("________上面拦截到_________");
        System.out.println(token);

        //String userId = request.getHeader("userId");
        if (StringUtils.isEmpty(token)) {
            AuthContextHolder.setUserId(1L);
        } else {
            //改
            Claims claims = JwtHelper.checkJWT(token);
            if (claims == null){
                //告诉登录过期，重新登录
                System.out.println("登录过期，重新登录");
            }

            Long userId = JwtHelper.getUserId(token);
            System.out.println("当前用户："+userId);
            if (StringUtils.isEmpty(userId)) {
                AuthContextHolder.setUserId(1L);
            } else {
                AuthContextHolder.setUserId(userId);
            }


        }
    }

}
